package com.zhangxiaofanfan.hotcode.second;

/**
 * <a href="https://leetcode.cn/problems/swap-nodes-in-pairs/?envType=study-plan-v2&envId=top-100-liked">两两交换链表中的节点</a>
 *
 * @author zhangxiaofanfan
 * @date 2024-05-28 23:10:55
 */
public class HotCode030 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        // head.next.next.next = new ListNode(4);
        HotCode030 hotCode = new HotCode030();
        hotCode.swapPairs(head);
    }

    public ListNode swapPairs(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode header = new ListNode();
        header.next = head;
        ListNode index = header, before, after;
        while (true) {
            before = index.next;
            if (before == null) {
                break;
            }
            after = before.next;
            if (after == null) {
                break;
            }
            index.next = after.next;
            after.next = before;
            before.next = index.next;
            index.next = after;
            index = before;
        }
        return header.next;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
